package com.wanmait.spacesys.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.alibaba.fastjson.JSONArray;
import com.wanmait.spacesys.dao.ArticleDAO;
import com.wanmait.spacesys.dao.SubjectDAO;
import com.wanmait.spacesys.vo.Article;
import com.wanmait.spacesys.vo.Managerinfo;
import com.wanmait.spacesys.vo.Subject;

@WebServlet("/ArticleController")
@MultipartConfig
public class ArticleController extends BaseController {
	private ArticleDAO articleDAO = new ArticleDAO();
	private SubjectDAO subjectDAO = new SubjectDAO();
	protected void findSubject(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		List<Subject> subjects = subjectDAO.findAll();
//		System.out.println(subjects.get(0).getName());
		request.setAttribute("subjects", subjects);
		try {
			this.forward("/web/manager/add-article.jsp", request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	protected void addArticle(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		String idStr = request.getParameter("subject_id");
		Integer subjectId = Integer.parseInt(idStr);
//		Managerinfo managerinfo= (Managerinfo)request.getSession().getAttribute("managerinfo");
//		Integer managerId = managerinfo.getId();
		Integer managerId =1;
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		Part part = request.getPart("pic");
		String fileName = this.savePicture(part, request, response);
		Article article = new Article();
		article.setContent(content);
		article.setSubjectId(subjectId);
		article.setManagerId(managerId);
		article.setPic(fileName);
		article.setTitle(title);
//		System.out.println(article);
		articleDAO.addArticle(article);
		
	}
	 
	public String savePicture(Part part,HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		String name = part.getSubmittedFileName();
//		System.out.println("part--"+part);
//		System.out.println("name--"+name);
		
		String ext = name.substring(name.lastIndexOf('.'));
		String fileName = UUID.randomUUID().toString()+ext;
		InputStream is = part.getInputStream();
		String realPath = this.getServletContext().getRealPath("/images/articleImages");
		File dir = new File(realPath);
		if(!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir,fileName);
		FileOutputStream fos = new FileOutputStream(file);
		byte[] buf = new byte[1024*8];
		int len = 0;
		while(true) {
			len = is.read(buf);
			if(len==-1) break;
			fos.write(buf,0,len);
		}
		fos.close();
		is.close();
		return fileName;
	}
	protected void updateArticle(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Managerinfo managerinfoFake = new  Managerinfo();
		managerinfoFake.setId(1);
		request.getSession().setAttribute("managetinfo", managerinfoFake);
		String title = request.getParameter("title");
		String content =request.getParameter("content");
		String subjectIdStr =  request.getParameter("subject");
		Integer subjectId = Integer.parseInt(subjectIdStr);
//		System.out.println("subjectId"+subjectId);
		String articleIdStr = request.getParameter("articleId");
		Integer articleId = Integer.parseInt(articleIdStr);
		Managerinfo manager =(Managerinfo) request.getSession().getAttribute("managetinfo");
//		System.out.println(manager);
//		System.out.println(manager.getId());
		
		Integer managerId = manager.getId();
		Part part = null;
		String pic="" ;
		part = request.getPart("newPicture");
		if(!part.getSubmittedFileName().equals("")) {
			pic = this.savePicture(part, request, response);
//			System.out.println("pic--"+pic);
		}
		Article article = new Article();
		article.setSubjectId(subjectId);
		article.setTitle(title);
		article.setManagerId(managerId);
		article.setContent(content);
		article.setId(articleId);
//		System.out.println("articleID--"+articleId);
		if(!pic.equals("")) {
			article.setPic(pic);
			articleDAO.updateArticle(article);
		}
		else {
			//未上传图片，保存原来的
			articleDAO.updatePart(article);
		}
		
		
		
	}
	protected void findSubjectAjax(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");
		List<Subject>subjects =  subjectDAO.findAll();
		JSONArray.writeJSONString(response.getWriter(), subjects);
	}
	protected void findArticleById(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/json;charset=utf-8");
			String idStr = request.getParameter("subjectId");
			Integer id = Integer.parseInt(idStr);
			List<Article>articles  = articleDAO.findById(id);
			JSONArray.writeJSONString(response.getWriter(),articles );
			
	}
	

		
		//查出所有的文章，进行显示。
//		protected void ajaxlist(HttpServletRequest request, HttpServletResponse response)
//				throws ServletException, IOException { 
//			String pageNumStr =  request.getParameter("pageNum");
//			int pageNum = 1;
//			try {
//				pageNum = Integer.parseInt(pageNumStr);
//			} catch (NumberFormatException e) {
//			}
//
//			int count =  articleDAO.getCount();
//			request.setAttribute("count", count);
//			
//			/*
//			 * List<Article> randomLists = articleDAO.randomList();
//			 * request.setAttribute("randomLists", randomLists);
//			 */
//			
//			List<Article> articles =  articleDAO.newFindAll(pageNum);
//			request.setAttribute("articles", articles);
//			request.getRequestDispatcher("/web/manager/localRefresh.jsp").forward(request, response);
//		}
		
		
		
		//显示出各个类别的所有内容
		protected void classification(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException { 
			String pageNumStr =  request.getParameter("pageNum");
			int pageNum = 1;
			try {
				pageNum = Integer.parseInt(pageNumStr);
			} catch (NumberFormatException e) {
		}
			//类别id是9的总条数
			String subjectIdStr =  request.getParameter("subjectId");
			Integer id = Integer.parseInt(subjectIdStr);
			
			int count =  articleDAO.getpaging(id);
			request.setAttribute("count", count);
			
			//显示最新内容
			List<Article> articles =  articleDAO.newSubject(id, pageNum);
			request.setAttribute("articles", articles);
			request.getRequestDispatcher("/web/manager/localRefresh.jsp").forward(request, response);
		}
		
		//模糊搜索
		protected void vague(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
			String retrieval =  request.getParameter("retrieval");
			String idStr =  request.getParameter("id");
			
			Integer id = Integer.parseInt(idStr);
			List<Article> articlesSearch =  articleDAO.findSearch(id,retrieval);
			request.setAttribute("articlesSearch", articlesSearch);

			request.getRequestDispatcher("/web/manager/localRefresh.jsp").forward(request, response);

		}
		
		
		//宇航产品显示方法
		protected void Aerospace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
			String pageNumStr =  request.getParameter("pageNum");
			int pageNum = 1;
			try {
				pageNum = Integer.parseInt(pageNumStr);
			} catch (NumberFormatException e) {
		}
			//类别id的总条数
			String subjectIdStr =  request.getParameter("subjectId");
			Integer id = Integer.parseInt(subjectIdStr);
			int count =  articleDAO.getpaging(id);
			request.setAttribute("count", count);
			
			List<Article> articles =  articleDAO.findProduct(id, pageNum);
			request.setAttribute("articles", articles);
			request.getRequestDispatcher("/web/ajaxSpace.jsp").forward(request, response);
			
}
		
		
		

		//航天英雄查询方法
		protected void spacehero(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
		{	
		  response.setCharacterEncoding("utf-8"); 
		  //String id = request.getParameter(id);
		  Integer  id =10;
		  List<Article>articles = articleDAO.spacehero(id);
		  request.setAttribute("articles", articles);			  
		  int count= articleDAO.showCount(id);
			request.setAttribute("count", count);
		  this.forward("/web/hero.jsp", request, response);
			
		}
		

		//分页的条数
		protected void ajaxlist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
		{
			
		      String pageNumStr  =request.getParameter("pageNum");
		      int pageNum=1;
		      
		      try {
					pageNum = Integer.parseInt(pageNumStr);
				} catch (NumberFormatException e) {
				}
		      
		        //页面是10的 
		      	String subjectId=request.getParameter("subjectId");	      	
		      	Integer id = Integer.parseInt(subjectId);
		      	
		      	int count = articleDAO.showCount(id);
		      	
		      	request.setAttribute("count", count);
		      	
		      	//查出航天英雄最新的文章
		        List<Article> articles = articleDAO.newSubjectt(id,pageNum);
		       
		        request.setAttribute("articles", articles);
		       
		        request.getRequestDispatcher("/web/ajaxshow.jsp").forward(request, response);
		        //this.forward("/web/hero.jsp", request, response);
		}
		
		// 按照首页航天英雄发布
		protected void consulting(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			response.setCharacterEncoding("UTF-8");
			
			response.setContentType("application/json;charset=utf-8");// 杰森格式对象
			List<Article> articles = articleDAO.findAllArticleze();
			
			//System.out.println(articles.get(0).getPubTime());
			JSONArray.writeJSONString(response.getWriter(), articles);

		}
		
		
		
		protected void findById(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {

			String ids = request.getParameter("id");
			Integer id = Integer.parseInt(ids);

			Article article = articleDAO.findByIds(id);
			/* article.setId(article.getId()+1); */
				
			request.setAttribute("article", article);
			
			this.forward("/web/index.jsp", request, response);

		}
		
	

	@Override
	protected void doDefault(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
	}
	
 


}
